<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽">
    </el-switch>
    <el-button v-if="draggable" @click="batchSave">保存拖拽</el-button>
    <el-button type="danger" @click="batchDel">批量删除</el-button>
    <el-tree
      :data="data"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>
          <el-button type="text" size="mini" @click="edit(data)">
            修改
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCategoryListTree,
  deleteCategoryByIds,
  getCategoryById,
  saveCategory,
  updateCategory,
  updateCategoryBatch,
} from '../../../../api/product/category'

export default {
  data() {
    return {
      pCid: [],
      title: "",
      data: [],
      draggable:false,
      expandedKey: [],
      dialogVisible: false,
      maxLevel: 0,
      updateNodes: [],
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 0,
        sort: 0,
        catId: null,
        productUnit: "",
        icon: "",
      },
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  methods: {
    handleNodeClick(data) {
      console.log(data);
    },
    //获取所有数据
    getMenus() {
      getCategoryListTree().then((response) => {
        this.data = response.data.data;
      });
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("tree drop: ", draggingNode, dropNode, dropType);
      //当前节点最新的父节点id
      let pCid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid)
      //当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //如果遍历的是当前正在拖拽的节点
          let catLevel = dropNode.level;
          if (siblings[i].level != draggingNode.level) {
            catLevel = siblings[i].level;
            //修改子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            sort: i,
            catId: siblings[i].data.catId,
            parentCid: pCid,
            catLevel: catLevel,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }

      //当前拖拽节点的最新层级
      console.log("updateNodes", this.updateNodes);
    },
    batchSave(){
      updateCategoryBatch(this.updateNodes).then((response) => {
        const result = response.data.code;
        if (result == 200) {
          this.$message({
            message: "菜单修改成功",
            type: "success",
          });
          //刷新菜单
          this.getMenus();
          //设置需要默认展开的菜单
          this.expandedKey = this.pCid
          this.updateNodes = []
          this.maxLevel = 0
          // this.pCid = 0
        } else {
          this.$message({
            message: "菜单修改失败",
            type: "error",
          });
        }
      });
    },
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      //被拖动的当前节点以及被拖动的父节点总层数不能大于3
      this.countNodeLevel(draggingNode);
      let deep = Math.abs(this.maxLevel - draggingNode.data.catLevel + 1);
      console.log("深度", deep);
      if (type == "inner") {
        // console.log(
        //   `this.maxLevel：${this.maxLevel}；draggingNode.data.catLevel：${draggingNode.data.catLevel}；dropNode.level：${dropNode.level}`
        // );
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },

    append(data) {
      console.log("append", data);
      this.title = "添加分类";
      this.dialogType = "add";
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;

      this.category.catId = null;
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.sort = 0;
      this.category.showStatus = 0;
    },

    submitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },

    edit(data) {
      this.dialogVisible = true;
      this.dialogType = "edit";
      this.title = "修改分类";
      getCategoryById(data.catId).then((response) => {
        const result = response.data.category;
        console.log(result);
        this.category.name = result.name;
        this.category.catId = result.catId;
        this.category.icon = result.icon;
        this.category.productUnit = result.productUnitz;
        this.category.parentCid = result.parentCid;
      });
    },

    //添加三级分类
    addCategory() {
      console.log("提交的三级分类数据", this.category);
      saveCategory(this.category).then((response) => {
        if (response.data.code == 200) {
          console.log(response);
          this.$message({
            message: "菜单保存成功",
            type: "success",
          });
          //关闭对话框
          this.dialogVisible = false;
          //刷新出新的菜单
          this.getMenus();
          //设置需要默认展开的菜单
          this.expandedKey = [this.category.parentCid];
        } else {
          this.$message({
            message: "菜单保存失败",
            type: "error",
          });
        }
      });
    },

    //修改三级分类数据
    editCategory() {
      const { catId, name, icon, productUnit } = this.category;
      const data = { catId, name, icon, productUnit };
      updateCategory(data).then((response) => {
        if (response.data.code == 200) {
          this.$message({
            message: "菜单修改成功",
            type: "success",
          });
          //关闭对话框
          this.dialogVisible = false;
          //刷新出新的菜单
          this.getMenus();
          //设置需要默认展开的菜单
          this.expandedKey = [this.category.parentCid];
        } else {
          this.$message({
            message: "菜单修改失败",
            type: "error",
          });
        }
      });
    },

    remove(node, data) {
      const ids = [data.catId];
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteCategoryByIds(ids).then((response) => {
            console.log(response.data);
            this.$message({
              message: "菜单删除成功",
              type: "success",
            });
            //刷新数据
            this.getMenus();
            //
            this.expandedKey = [node.parent.data.catId];
          });
        })
        .catch(() => {
          this.$message({
            message: "取消删除",
            type: "warning",
          });
        });
      // console.log("remove",node,data)
    },
    batchDel(){
      let catIds = []
      let checkNodes = this.$refs.menuTree.getCheckedNodes()
      console.log(checkNodes)
      for(let i=0;i < checkNodes.length; i++){
        catIds.push(checkNodes[i].catId)
      }
      this.$confirm(`是否删除选中的${catIds.length}个菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
          deleteCategoryByIds(catIds).then((response) => {
            console.log(response.data);
            this.$message({
              message: "菜单删除成功",
              type: "success",
            });
            //刷新数据
            this.getMenus();
            //展开的
            this.expandedKey = [node.parent.data.catId];
          });
        })
        .catch(() => {
          this.$message({
            message: "取消删除",
            type: "warning",
          });
        });

    }
  },
  created() {
    this.getMenus();
  },
};
</script>

<style>
</style>